/*
 * @Author: w
 * @Date: 2022-02-10 22:57:13
 * @Description: 2. 两数相加
 */

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */

/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
// 我
var addTwoNumbers = function (l1, l2) {
  let jinwei = 0; // carry
  let list = new ListNode(); // result
  let lNode = list; // current
  while (true) {
    let value = l1.val + l2.val + jinwei;
    lNode.val = value % 10;
    jinwei = parseInt(value / 10);
    // 应该作为while的条件
    if (l1.next == undefined && l2.next == undefined) {
      if (jinwei) {
        lNode.next = new ListNode();
        // val 直接放在new ListNode参数中
        lNode.next.val = jinwei;
      }
      return list;
    }

    l1 = l1.next || { val: 0 };
    l2 = l2.next || { val: 0 };
    // 应该创建node 在计算出val时
    lNode.next = new ListNode();
    lNode = lNode.next;
  }
};

// 官方
var addTwoNumbers = function (l1, l2) {
  let head = null,
    tail = null;
  let carry = 0;
  while (l1 || l2) {
    const n1 = l1 ? l1.val : 0;
    const n2 = l2 ? l2.val : 0;
    const sum = n1 + n2 + carry;
    if (!head) {
      head = tail = new ListNode(sum % 10);
    } else {
      tail.next = new ListNode(sum % 10);
      tail = tail.next;
    }
    carry = Math.floor(sum / 10);
    if (l1) {
      l1 = l1.next;
    }
    if (l2) {
      l2 = l2.next;
    }
  }
  if (carry > 0) {
    tail.next = new ListNode(carry);
  }
  return head;
};

// 最快
var addTwoNumbers = function (l1, l2) {
  let result = new ListNode();
  let current = result;
  let carry = 0;
  while (l1 || l2) {
    const x = l1 ? l1.val : 0;
    const y = l2 ? l2.val : 0;
    const total = x + y + carry;
    current.next = new ListNode(total % 10);
    current = current.next;
    if (l1) l1 = l1.next;
    if (l2) l2 = l2.next;
    carry = Math.floor(total / 10);
  }
  if (carry) current.next = new ListNode(carry);
  return result.next;
};
